//! Copyright 2012 Xicut Technology, Inc.
//! All rights reserved
//!
#include "Config.h"
#include "StrLib.h"
#include "enc28j60.h"
#include "arp.h"
#include "icmp.h"
#include "udp.h"

#include "TcpIp.h"


void cTcpIp::InitReset()
{
    cIP::InitReset();
    cEnc28j60::InitReset(cIP::GetMacAddr());
}


void cTcpIp::RunOne()
{
    U8 clientMac[cIP::MAC_ADDR_LEN];
    U8 clientIP[cIP::IP_ADDR_LEN];
    // you can change rx,tx buffer size in includes.h
    U8 rxtx_buffer[cIP::MAX_RXTX_BUFFER];
    U16 plen;

    // get new packet
    plen = cEnc28j60::ReceivePacket( rxtx_buffer, cIP::MAX_RXTX_BUFFER );

    //plen will ne unequal to zero if there is a valid packet (without crc error)
    if(plen==0)
        return;

    // copy client mac address from buffer to client mac variable
    cStrLib::Strcpy( clientMac, &rxtx_buffer[ cIP::MAC_SRC_MAC_POS ], cIP::MAC_ADDR_LEN );

    // check arp packet if match with avr ip let's send reply
    if ( true == cArp::IsArpPacket( rxtx_buffer, cArp::ARP_OPCODE_REQUEST_V ) )
    {
        cArp::SendReply ( rxtx_buffer, clientMac );
        return;
    }

    // check ip packet send to avr or not?
    if ( false == cIP::IsValidPacket(rxtx_buffer) )
    {
        return;
    }

    // get client ip address
    cStrLib::Strcpy( clientIP, &rxtx_buffer[ cIP::IP_SRC_IP_P ], cIP::IP_ADDR_LEN );

    // check packet if packet is icmp packet let's send icmp echo reply
    if ( cIcmp::SendReply( rxtx_buffer, clientMac, clientIP ) )
    {
        return;
    }

    // check packet if packet is udp packet let's send udp reply
    if (true == cUdp::UDPReceive ( rxtx_buffer, clientMac, clientIP ))
    {
        return;
    }
// 
//     if (true == cTcp::TCP_process ( rxtx_buffer, clientMac, clientIP ))
//     {
//         return;
//     }
}
